<template>
  <div class="login-container">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="loginform"
      label-width="100px"
      class="demo-ruleForm"
    >
      <h2 class="login-title">文具1号商城管理系统-登录</h2>
      <el-form-item label="用户名" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="psw">
        <el-input v-model="ruleForm.psw"></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="checked">七天免登录</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
        <el-button type="primary" @click="goto">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import userApi from "../../api/userApi";
import { setToken, setUser } from "../../utils/auth"; //cookie相关方法
export default {
  data() {
    return {
      ruleForm: {
        name: "",
        psw: ""
      },
      rules: {
        //表单检验
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        psw: [{ required: true, message: "请输入密码", trigger: "change" }]
      },
      checked: false
    };
  },
  methods: {
    goto() {
      this.$router.push("/reg");
    },

    //功能：点击登录
    login() {
      this.$refs.loginform.validate(valid => {
        //valid为表单验证结果：true就是验证全部通过
        // console.log(valid, 9900);
        if (valid) {
          let { name, psw } = this.ruleForm;
          let password = this.$md5(psw); //登录记得加密再匹配
          userApi.login(name, password).then(res => {
            // console.log(res.data, 6688);
            if (res.data.flag) {
              //登录成功：把token和uid存到本地存储-cookie
              if (this.checked) {
                //要保留7天
                setToken(res.data.token, 7);
                setUser(res.data.uid, 7);
              } else {
                //不用保留7天：会话级别，关闭浏览器销毁
                setToken(res.data.token);
                setUser(res.data.uid);
              }

              //登录成功跳到首页
              this.$router.push({ path: "/home", query: { name } });
            } else {
              //登录失败
            }
          });
        } else {
          // alert("不可以注册!");
          // this.$message({
          //   message: "请填写全部信息",
          //   type: "error"
          // });
          return false;
        }
      });
    }
  },

  //今天页面就获取用户
  created() {
    this.ruleForm.name = this.$route.query.name;
  }
};
</script>

<style scoped>
@import "../../assets/sass/login.scss";
</style>